package m.jclecai.com.activity;


import android.content.Intent;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.adapter.BankListAdapter;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.BankBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.inter.OnCautionDialogConfirmListener;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.responseBody.BankBody;
import m.jclecai.com.utils.http.responseBody.BaseBody;
import m.jclecai.com.view.CautionDialog;

/**
 * Created by ZD on 2017/5/22.
 */

public class BankCardListActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener {


    @BindView(R.id.pl_list)
    PullToRefreshListView plList;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    BankListAdapter adapter;
    List<BankBean> mList;

    @Override
    public int getContentView() {
        return R.layout.activity_bank_list;
    }

    @Override
    protected void initView() {
        super.initView();
        setTitle("我的银行卡");
        leftOptionText("");
        rightOptionText("", R.drawable.menu_add);
        plList.setOnRefreshListener(this);

        ListView refreshableView = plList.getRefreshableView();
        showLoadingLayout(plList);
    }

    @Override
    protected void initData() {
        super.initData();
        mList = new ArrayList<>();
        adapter = new BankListAdapter(this, mList);
        plList.setAdapter(adapter);

        adapter.setOnItemListener(new BankListAdapter.OnItemListener() {
            @Override
            public void onClickDel(final BankBean bankBean) {
                //具体哪个条目点击了删除操作；
                CautionDialog CautionDialog = new CautionDialog(BankCardListActivity.this, "是否清除本次选号", new OnCautionDialogConfirmListener() {
                    @Override
                    public void onCancelListener() {
                    }

                    @Override
                    public void onConfirmListener() {
                        delBank(bankBean);
                    }
                });
                CautionDialog.show();
            }
            @Override
            public void onClickSetDefault(View view, boolean isChecked, BankBean bankBean) {
                //具体将某个item设置为默认的的；
                if (mList != null) {
                    for (BankBean bean : mList) {
                        if (!bean.equals(bankBean)) {
                            bean.setCheck(false);
                        } else {
                            bankBean.setCheck(isChecked);
                        }
                    }
                }

                adapter.notifyDataSetChanged();
            }
        });
        getBankList();
    }

    //获取列表
    void getBankList() {
        Map<String, String> map = new HashMap<>();
        map.put("user", PreferenceUtil.getUserName(this));
        map.put("password", PreferenceUtil.getPassword(this));
        HttpManager.postAsyn(Constant_Url.GET_USER_BANKS, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                plList.onRefreshComplete();
                dissDialog();
                MyToast.showToast(BankCardListActivity.this, getString(R.string.error_network));
                showInternetOffLayout();
            }

            @Override
            public void onResponse(String response) {
                plList.onRefreshComplete();
                dissDialog();
                closeLoadingLayout();
                BankBody bankBody = FastOk.get(response, BankBody.class);
                if (bankBody != null) {
                    if (bankBody.getStatus() == 0) {
                        mList.clear();
                        mList.addAll(bankBody.getBank());
                        setDefaultBankBean();
                        adapter.notifyDataSetChanged();
                    } else if (bankBody.getStatus() == 1001) {
                        //删除了所有的数据之后
                        mList.clear();
                        adapter.notifyDataSetChanged();
                        PreferenceUtil.clearWithDrawBank(BankCardListActivity.this);
                    }
                    if (mList.size() <= 0)
                        showEmptyLayout();
                } else {
                    showExceptionLayout();
                }
            }
        }, map);
    }

    /**
     * 这里是设置默认的银行卡
     */
    private void setDefaultBankBean() {

        if (mList.size()<=0 && mList==null) {
            return;
        }

        BankBean defaultWithDrawBank = PreferenceUtil.getDefaultWithDrawBank(this);
        if (defaultWithDrawBank != null) {
            for (BankBean bankBean : mList) {
                if(bankBean.getBankno().equals(defaultWithDrawBank.getBankno())){
                    bankBean.setCheck(true);
                }else{
                    bankBean.setCheck(false);
                }
            }
        }else{
            mList.get(0).setCheck(true);
            PreferenceUtil.setDefaultWithDrawBank(this,mList.get(0));
        }
    }

    void delBank(final BankBean bankBean) {
        Map<String, String> map = new HashMap<>();
        map.put("user", PreferenceUtil.getUserName(this));
        map.put("password", PreferenceUtil.getPassword(this));
        String delBankId = bankBean.getId();
        map.put("id", delBankId);
        showDialog();
        HttpManager.postAsyn(Constant_Url.DEL_USER_BANK, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                MyToast.showToast(BankCardListActivity.this, getString(R.string.error_network));
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                BaseBody bankBody = FastOk.get(response, BaseBody.class);
                if (bankBody != null) {
                    DisPlay(bankBody.getMessage());
                    if (bankBody.getStatus() == 0) {
                        mList.remove(bankBean);
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    DisPlay(getString(R.string.error_network));
                }
            }
        }, map);
    }

    String getDelBankId() {
        String ids = "";
        for (int i = 0; i < mList.size(); i++) {
            BankBean bankBean = mList.get(i);
            if (bankBean.isCheck()) {
                ids += mList.get(i).getId();
                if (i < mList.size() - 1)
                    ids += ",";
            }
        }
        return ids;
    }

    @OnClick(R.id.tv_sure)
    void addCard() {
        if (tvRightOption == null) return;
        //在这里我们判断一下，用户是否绑定了用户名和密码；
        if (PreferenceUtil.readBoolean(this, PreferenceUtil.IS_USER_NAME_EMPTY, false)) {
            //这里我们是跳转到注册用户名和密码的界面；
            DisPlay("先绑定用户名和密码！！");
            HashMap<String, String> map = new HashMap<>();
            map.put("nickname", PreferenceUtil.getUserName(this));
            map.put("password", PreferenceUtil.getPassword(this));
            //.putExtra("param", JSON.toJSONString(threeLoginPairmsMap)
            Intent intent = RegisterActivity.getIntent(this, false);
            intent.putExtra("param", JSON.toJSONString(map));
            //这里是需要nickname,password的
            startActivityForResult(intent, Constant_Result.REQUEST_BIND_USERNAME_PASSWORD);
            return;
        } else {
            startActivityForResult(new Intent(this, BindbankCardActivity.class), Constant_Result.BINDBANK);
        }
    }

    @OnClick(R.id.tv_right_option)
    void showDel() {
        addCard();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //添加卡成功
        if (requestCode == Constant_Result.BINDBANK) {

            if (resultCode == RESULT_OK) {
                getBankList();
            }
            setResult(resultCode);

        } else if (requestCode == Constant_Result.REQUEST_BIND_USERNAME_PASSWORD) {
            if (resultCode == RESULT_OK) {
                startActivityForResult(new Intent(this, BindbankCardActivity.class), Constant_Result.BINDBANK);
            }
        }

    }

    @Override
    protected void close() {
        onBackPressed();
    }


    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        getBankList();
    }

    @Override
    public void OnRetry(String btnMessage) {
        showLoadingLayout(plList);
        getBankList();
    }

    @Override
    public void onBackPressed() {

        BankBean bankBean=null;
        //设置选中的银行卡
        if (!mList.isEmpty()) {
            //银行卡列表不为空：
            for (BankBean bean : mList) {
                if (bean.isCheck()) {
                    bankBean=bean;
                    break;
                }
            }
        }
        if(bankBean == null && !mList.isEmpty()){
            DisPlay("请选择默认的银行卡");
        }else if(bankBean!=null && !mList.isEmpty()){
            //这里是需要设置银行卡的
            PreferenceUtil.setDefaultWithDrawBank(this,bankBean);
            finish();
        }else{
            //这里表示没有一张银行卡：
            PreferenceUtil.clearWithDrawBank(BankCardListActivity.this);
            finish();
        }
    }

}
